#include <iostream>
/* You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.  */
/* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) */
/* Output: 7 -> 0 -> 8 */
/* [解法]链表逐个相加 */
/* Definition for singly-linked list. */
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution 
{
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) 
    {
        ListNode *resultList = new ListNode(0);
        ListNode *tempNode = resultList;

        int tempSum = 0;
        int tempVal1;
        int tempVal2;
        int carry = 0;
        while(l1 != NULL || l2 != NULL)
        {
            if(l1 != NULL)
            {
                tempVal1 = l1->val;
                l1 = l1->next;
            }
            else
                tempVal1 = 0;

            if(l2 != NULL)
            {
                tempVal2 = l2->val;
                l2 = l2->next;
            }
            else
                tempVal2 = 0;

            tempSum = tempVal1 + tempVal2 + carry;
            tempNode->next = new ListNode(tempSum%10);
            carry = tempSum/10;
            tempNode = tempNode->next;
        }

        if(carry == 1)
            tempNode->next = new ListNode(1);

        return resultList->next;
    }
};

int main(){
    Solution sln;
    ListNode *L1 = new ListNode(2);
    L1->next = new ListNode(4);
    L1->next->next = new ListNode(3);

    ListNode *L2 = new ListNode(5);
    L2->next = new ListNode(6);
    L2->next->next = new ListNode(4);

    ListNode *resultList;
    resultList = sln.addTwoNumbers(L1, L2); 

    return 0;
}
